﻿using AutoMapper;
using ManagementApi.Models;
using ManagementApi.Models.System.Flow;
using ManagementApi.Models.System.TableLog;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules;
using PmSoft.ApplicationContext;
using PmSoft.Logging;

namespace ManagementApi.Controllers.SystemManage.Logs
{
    /// <summary>
    /// 系统表操作日志
    /// </summary>
    [Route("/api/v1/systable")]
    [ApiController]
    [Authorize(Roles = "SysUser")]
    public class TableLogController : ControllerBase
    {
        private readonly SysTableLogService sysTableLogService;
        public readonly IApplicationContext applicationContext;
        private readonly IMapper mapper;

        public TableLogController(SysTableLogService sysTableLogService, IApplicationContext applicationContext, IMapper mapper)
        {
            this.sysTableLogService = sysTableLogService;
            this.applicationContext = applicationContext;
            this.mapper = mapper;
        }

        /// <summary>
        /// 获取日志（分页）
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns></returns>
        [HttpGet("page")]
        public ApiResult<PageDto<SysTableLogDto>> GetTableLogs([FromQuery] SysTableLogQuery query, int pageNum = 1, int pageSize = 20)
        {
            var sysTableLogs = sysTableLogService.GetLogs(query, pageNum, pageSize);
            var dtos = sysTableLogs.AsPageDto(source => { return source.AsDto(); });
            return ApiResult<PageDto<SysTableLogDto>>.Success(dtos);
        }

        /// <summary>
        /// 获取日志详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}/form")]
        public ApiResult<SysTableLogForm> GetTableLog(int id)
        {
            SysTableLog? sysTableLog = sysTableLogService.GetLog(id);
            if (sysTableLog == null) return ApiResult<SysTableLogForm>.Failure("操作日志不存在");
            return ApiResult<SysTableLogForm>.Success(sysTableLog.AsForm());
        }
    }
}